package org.feuyeux.opentracing;

import com.google.common.collect.ImmutableMap;
import io.opentracing.Scope;
import io.opentracing.Span;
import io.opentracing.Tracer;
import lombok.extern.slf4j.Slf4j;
import org.feuyeux.opentracing.lib.HttpClient;
import org.feuyeux.opentracing.lib.Tracing;

import java.util.Map;

@Slf4j
public class Hello {

    private final Tracer tracer;
    private final HttpClient client;

    private Hello(Tracer tracer) {
        this.tracer = tracer;
        this.client = new HttpClient(tracer);
    }

    private void sayHello() {
        Span span = tracer.buildSpan("hello").start();
        try (Scope scope = tracer.scopeManager().activate(span)) {
            span.setTag("hello-at", System.currentTimeMillis());
            askA();
        } finally {
            span.finish();
        }
    }

    private String askA() {
        Span span = tracer.buildSpan("ask-a-x").start();
        try (Scope scope = tracer.scopeManager().activate(span)) {
            Map<String, String> paramMap = ImmutableMap.of(
                    "r", "RRR",
                    "s", "S1,S2,S3,S4,S5",
                    "t", "TT");
            String xResult = client.getHttp(8081, "x", paramMap);
            span.log(ImmutableMap.of("event", "askA", "value", xResult));
            return xResult;
        } finally {
            span.finish();
        }
    }

    public static void main(String[] args) {
        try (Tracer tracer = Tracing.init("client")) {
            new Hello(tracer).sayHello();
        }
    }
}
